<template>
  <div class="category-view">
    <div class="category-layout">
      <CategoryNav />
      <div class="category-content">
        <div class="category-header">
          <h1 class="category-title">水果专区</h1>
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索水果"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #suffix>
                <el-icon class="search-icon" @click="handleSearch"><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
        <div v-if="loading" class="loading">加载中...</div>
        <div v-else-if="error" class="error">{{ error }}</div>
        <div v-else class="products-grid">
          <ProductCard 
            v-for="product in paginatedProducts" 
            :key="product.id" 
            :product="product"
            :initial-favorite="favoriteIds.has(product.id)"
          />
        </div>
        
        <!-- 分页组件 -->
        <div class="pagination" v-if="totalPages > 1">
          <el-button 
            :disabled="currentPage === 1"
            @click="changePage(currentPage - 1)"
          >
            上一页
          </el-button>
          <div class="page-numbers">
            <el-button 
              v-for="page in displayedPages" 
              :key="page"
              :type="currentPage === page ? 'primary' : ''"
              @click="changePage(page)"
            >
              {{ page }}
            </el-button>
          </div>
          <el-button 
            :disabled="currentPage === totalPages"
            @click="changePage(currentPage + 1)"
          >
            下一页
          </el-button>
        </div>
      </div>
    </div>
    <BackToTop />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from 'vue'
import CategoryNav from '../../components/CategoryNav.vue'
import ProductCard from '../../components/ProductCard.vue'
import BackToTop from '@/components/BackToTop.vue'
import { Search } from '@element-plus/icons-vue'
import { getProductsByCategoryId, searchByName, getFavoriteList } from '@/axios/product'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const products = ref([])
const loading = ref(true)
const error = ref(null)
const searchKeyword = ref('')
const favoriteIds = ref(new Set()) // 存储收藏的商品ID

// 分页相关
const itemsPerPage = 6 // 每页显示6个商品
const currentPage = ref(1)
const totalPages = computed(() => Math.ceil(products.value.length / itemsPerPage))

// 当前页的商品
const paginatedProducts = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage
  const end = start + itemsPerPage
  return products.value.slice(start, end)
})

// 显示的页码（最多显示5个页码）
const displayedPages = computed(() => {
  if (totalPages.value <= 5) {
    return Array.from({ length: totalPages.value }, (_, i) => i + 1)
  }
  
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, start + 4)
  
  return Array.from({ length: end - start + 1 }, (_, i) => start + i)
})

// 更改页码
const changePage = (page) => {
  currentPage.value = page
  // 保存当前页码到 sessionStorage
  sessionStorage.setItem('fruitListCurrentPage', page)
  // 滚动到页面顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const fetchFavorites = async () => {
  try {
    const response = await getFavoriteList()
    if (response && Array.isArray(response)) {
      favoriteIds.value = new Set(response.map(item => item.id))
    }
  } catch (err) {
    console.error('获取收藏列表失败:', err)
  }
}

const fetchProducts = async () => {
  try {
    loading.value = true
    const response = await getProductsByCategoryId(3) // 3为水果分类ID
    
    if (response.code === 1) {
      // 后端返回的是 ProductFlVO 列表，直接使用
      products.value = response.data
        .filter(item => item.status !== 0 && item.stock >= 1) // 过滤掉status为0和库存小于1的商品
        .map(item => ({
          ...item,
          unit: '500g',
          image: item.image || 'https://images.unsplash.com/photo-1607623814075-e51df1bdc82f?w=500&auto=format&fit=crop&q=60'
        }))
      
      // 恢复之前保存的页码
      const savedPage = sessionStorage.getItem('fruitListCurrentPage')
      if (savedPage) {
        const page = parseInt(savedPage)
        // 确保页码有效
        if (page > 0 && page <= Math.ceil(products.value.length / itemsPerPage)) {
          currentPage.value = page
        }
      }
    } else {
      error.value = response.msg || '获取商品列表失败'
    }
  } catch (err) {
    error.value = '获取商品列表失败，请稍后重试'
    console.error('Error fetching products:', err)
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = async () => {
  const keyword = searchKeyword.value.trim()
  if (!keyword) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  loading.value = true
  try {
    console.log('开始搜索商品:', keyword)
    const response = await searchByName(keyword, 3) // 3为水果分类ID
    
    if (response && response.code === 1) {
      products.value = response.data
        .filter(item => item.status !== 0 && item.stock >= 1) // 过滤掉status为0和库存小于1的商品
        .map(item => ({
          ...item,
          unit: '500g',
          image: item.image || 'https://images.unsplash.com/photo-1607623814075-e51df1bdc82f?w=500&auto=format&fit=crop&q=60'
        }))
      if (products.value.length === 0) {
        ElMessage.info('未找到相关商品')
      }
    } else {
      error.value = response?.msg || '搜索失败'
      ElMessage.error(error.value)
    }
  } catch (err) {
    console.error('搜索失败:', err)
    error.value = '搜索失败，请稍后重试'
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

// 组件卸载前的处理
onBeforeUnmount(() => {
  // 如果是跳转到商品详情页，则保留页码，否则清除
  if (!router.currentRoute.value.path.includes('/product/')) {
    sessionStorage.removeItem('fruitListCurrentPage')
  }
})

onMounted(async () => {
  await fetchFavorites() // 先获取收藏列表
  await fetchProducts() // 再获取商品列表
})
</script>

<style scoped>
.category-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.category-layout {
  display: flex;
  gap: 30px;
}

.category-content {
  flex: 1;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  min-height: 80px;
}

.category-title {
  font-size: 32px;
  color: #2c3e50;
  font-weight: 600;
  margin: 0;
  line-height: 1;
}

.loading, .error {
  text-align: center;
  padding: 40px;
  font-size: 18px;
  color: #666;
}

.error {
  color: #e74c3c;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.search-box {
  width: 300px;
}

.search-icon {
  cursor: pointer;
  font-size: 20px;
  color: #409EFF;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  gap: 10px;
}

.page-numbers {
  display: flex;
  gap: 5px;
}

@media (max-width: 768px) {
  .category-layout {
    flex-direction: column;
  }
  
  .category-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
    min-height: auto;
  }
  
  .search-box {
    width: 100%;
  }
  
  .pagination {
    flex-wrap: wrap;
  }
}
</style> 